package com.company.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.aop.annotation.LogAnnotation;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.Func;
import com.company.project.entity.SysDept;
import com.company.project.entity.SysUser;
import com.company.project.mapper.SysDeptMapper;
import com.company.project.service.DeptService;
import com.company.project.service.HttpSessionService;
import com.company.project.service.RoleService;
import com.company.project.service.UserService;
import com.company.project.vo.resp.DeptRespNodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 部门管理
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@RequestMapping("/sys")
@RestController
@Api(tags = "组织模块-机构管理")
public class DeptController {
    @Resource
    private DeptService deptService;
    @Resource
    private HttpSessionService httpSessionService;
    @Resource
    private UserService userService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private RoleService roleService;
    @PostMapping("/dept")
    @ApiOperation(value = "新增组织接口")
    @LogAnnotation(title = "机构管理", action = "新增组织")
    @RequiresPermissions("sys:dept:add")
    public DataResult addDept(@RequestBody @Valid SysDept vo) {
        vo.setUserid(httpSessionService.getCurrentUserId());
        deptService.addDept(vo);
        return DataResult.success();
    }

    @DeleteMapping("/dept/{id}")
    @ApiOperation(value = "删除组织接口")
    @LogAnnotation(title = "机构管理", action = "删除组织")
    @RequiresPermissions("sys:dept:deleted")
    public DataResult deleted(@PathVariable("id") String id) {
        deptService.deleted(id);
        return DataResult.success();
    }

    @PutMapping("/dept")
    @ApiOperation(value = "更新组织信息接口")
    @LogAnnotation(title = "机构管理", action = "更新组织信息")
    @RequiresPermissions("sys:dept:update")
    public DataResult updateDept(@RequestBody SysDept vo) {
        if (StringUtils.isEmpty(vo.getId())) {
            return DataResult.fail("id不能为空");
        }
        deptService.updateDept(vo);
        return DataResult.success();
    }

    @GetMapping("/dept/{id}")
    @ApiOperation(value = "查询组织详情接口")
    @LogAnnotation(title = "机构管理", action = "查询组织详情")
    @RequiresPermissions("sys:dept:detail")
    public DataResult detailInfo(@PathVariable("id") String id) {
        return DataResult.success(deptService.getById(id));
    }

    @GetMapping("/dept/tree")
    @ApiOperation(value = "树型组织列表接口")
    @LogAnnotation(title = "机构管理", action = "树型组织列表")
    @RequiresPermissions(value = {"sys:user:list","sys:user:update", "sys:user:add", "sys:dept:add", "sys:dept:update"}, logical = Logical.OR)
    public DataResult getTree(@RequestParam(required = false) String deptId) {
        //通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        SysUser user = userService.getById(userId);
        return DataResult.success(deptService.deptTreeList(user.getDeptId(), false,userId));
    }

    @GetMapping("/depts")
    @ApiOperation(value = "获取机构列表接口")
    @LogAnnotation(title = "机构管理", action = "获取所有组织机构")
    @RequiresPermissions("sys:dept:list")
    public DataResult getDeptAll() {
        //通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        SysUser sysUser = userService.getById(userId);
        //管理员可查看全部 其他能看自己下级
        List<SysDept> deptList = new ArrayList<>();
        List<SysDept> sysDepts = new ArrayList<>();
        //0 为管理员可以看全部的
        if(StringUtils.equals("0",sysUser.getDeptId())){
            deptList = deptService.list();
        } else{
            List<String> sysRoleNames = roleService.getRoleNames(userId);
            String roleName = sysRoleNames.get(0);//自己的角色/
            LambdaQueryWrapper<SysDept> queryWrapperDept = Wrappers.lambdaQuery();
            if (Func.equals("总经理",roleName)) {
                queryWrapperDept = Wrappers.lambdaQuery();
                queryWrapperDept.eq(SysDept::getUserid, userId);
                //所有部门
                deptList = sysDeptMapper.selectList(queryWrapperDept);
            } else {
                queryWrapperDept = Wrappers.lambdaQuery();
                SysDept dept = sysDeptMapper.selectById(sysUser.getDeptId());
                queryWrapperDept.likeLeft(SysDept::getRelationCode, dept.getDeptNo());
                //所有部门
                deptList = sysDeptMapper.selectList(queryWrapperDept);
            }

            queryWrapperDept.orderByAsc(SysDept::getPid);
            queryWrapperDept.last("limit 1");
            //最大的部门
            sysDepts = sysDeptMapper.selectList(queryWrapperDept);
        }
        deptList.parallelStream().forEach(entity -> {
            SysDept parentDept = deptService.getById(entity.getPid());
            if (parentDept != null) {
                entity.setPidName(parentDept.getName());
            }
        });
        //设置最大部门PID treeSpid 需求pid为0
        for (int i = 0; i < deptList.size(); i++) {
            if(sysDepts.size()>0&&StringUtils.equals(deptList.get(i).getId(),sysDepts.get(0).getId())) {
                deptList.get(i).setPid("0");
            }
        }
        return DataResult.success(deptList);
    }

}
